/**
 * Created by Administrator on 2018/11/1.
 */

var user = getUser();
console.log(user);
var token = window.localStorage.getItem("token");

$(function () {

    var pieChartCanvas = $('#pieChart').get(0).getContext('2d');
    var pieChart = new Chart(pieChartCanvas);
    var pieOptions = {
        //Boolean - Whether we should show a stroke on each segment
        segmentShowStroke: true,
        //String - The colour of each segment stroke
        segmentStrokeColor: '#fff',
        //Number - The width of each segment stroke
        segmentStrokeWidth: 2,
        //Number - The percentage of the chart that we cut out of the middle
        percentageInnerCutout: 50, // This is 0 for Pie charts
        //Number - Amount of animation steps
        animationSteps: 100,
        //String - Animation easing effect
        animationEasing: 'easeOutBounce',
        //Boolean - Whether we animate the rotation of the Doughnut
        animateRotate: true,
        //Boolean - Whether we animate scaling the Doughnut from the centre
        animateScale: false,
        //Boolean - whether to make the chart responsive to window resizing
        responsive: true,
        // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
        maintainAspectRatio: true,
        //String - A legend template
        legendTemplate: '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'
    };
    // 项目分布统计
    $.getJSON(baseURL + 'generator/projectentity/countProjectStatus/' + user.userId + '/' + user.roleIdList,function (r) {
        // console.log(r);
        var projectNums = r.projectStatus;
        // console.log(projectNums);
        /*var data = {
         "0": 3, // 进展中
         "1": 2, // 已完成
         "2": 1  // 已超期
         };*/
        if (!projectNums['0']) {
            projectNums['0'] = 0;
        }
        if (!projectNums['1']) {
            projectNums['1'] = 0
        }
        if (!projectNums['2']) {
            projectNums['2'] = 0
        }
        if (!projectNums['3']) {
            projectNums['3'] = 0
        }
        // console.log(projectNums);
        var PieData = [
            {
                value: Number(projectNums['0']),
                color: '#00c0ef',
                highlight: '#00c0ef',
                label: '进行中'
            }, {
                value: Number(projectNums['1']),
                color: '#00a65a',
                highlight: '#00a65a',
                label: '已完成'
            }, {
                value: Number(projectNums['2']),
                color: '#f56954',
                highlight: '#f56954',
                label: '已超期'
            }, {
                value: Number(projectNums['3']),
                color: '#F51F14',
                highlight: '#F51F14',
                label: '已终止'
            }
        ];
        $('#p-total-num').text(Number(projectNums['0']) + Number(projectNums['1']) + Number(projectNums['2'])+ Number(projectNums['3']));
        pieChart.Doughnut(PieData, pieOptions);
    });

    // 待办任务 滚动初始化
    $('#task-list').slimScroll({
        height: '250px'
    });

    // 待办任务
    $.get(baseURL + 'generator/pojecttask/getDoingTaskList/' + user.userId + '/' + user.roleIdList, function (r) {
        // console.log(r);
        var taskList = r.doingTask;

        if (taskList.length > 0) {
            $('#task-bubble').text(taskList.length);
        }

        var liHtml = '';
        for (var i = 0; i < taskList.length; i++) {
            var tempClass = '';
            var taskStatus = '';
            if (taskList[i].taskState == 0) {
                tempClass = 'label label-primary';
                taskStatus = '已提交';
            } else if (taskList[i].taskState == 2) {
                tempClass = 'label label-danger';
                taskStatus = '已驳回';
            } else if (taskList[i].taskState == 3) {
                tempClass = 'label label-info';
                taskStatus = '进行中';
            }
            // console.log(typeof taskList[i].differentialTime);
            var hintHtml = '';
            var timeClass = '';
            if (taskList[i].differentialTime > 0) {
                // 未超期
                hintHtml = taskList[i].differentialTime + '天后截止';
                timeClass = 'label label-info';
            } else if (taskList[i].differentialTime == 0) {
                // 即将超期
                hintHtml = '今天截止';
                timeClass = 'label label-warning';
            } else {
                // 已超期
                hintHtml = '已超期' + Math.abs(taskList[i].differentialTime) + '天';
                timeClass = 'label label-danger';
            }
            liHtml += '<li data-projectId="' + taskList[i].projectId + '">' +
                        '<span><i class="fa fa-ellipsis-v"></i> <i class="fa fa-ellipsis-v"></i></span>' +
                        '<span class="text">' + taskList[i].projectName + '</span>' +
                        '<small class="' + tempClass + '">' + taskList[i].taskName + ' ' + taskStatus + '</small>' +
                        '<small class="' + timeClass + '"><i class="fa fa-clock-o"></i> ' + hintHtml + '</small>' +
                    '</li>'
        }
        $('#todo-list').html(liHtml)
            .on('click', 'li', function (e) {
                console.log(this);
                console.log($(this).attr('data-projectId'));

                var projectId = $(this).attr('data-projectId');
                var pWindow = window.parent;
                // 改变首页的 indexVm 的 data，触发 updated
                pWindow.indexVm.main = 'modules/project/projectdetails.html?projectId=' + projectId;

                pWindow.location.hash = 'modules/project/projectdetails.html?projectId=' + projectId;
                /*var oIframe = $('#main-content iframe', pWindow.document);
                pWindow.location.hash = 'modules/project/projectdetails.html?projectId=' + projectId;
                oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + projectId);*/
            });
    });

    // 项目检索
    $("#jqGrid").jqGrid({
        url: baseURL + 'generator/projectentity/doingList/' + user.userId + '/' + user.roleIdList,
        datatype: "json",
        colModel: [
            {label: '项目编号', name: 'projectNumber', sortable: false, index: 'project_number', width: 80},
            {label: '项目名称', name: 'projectName', sortable: false, index: 'project_name'},
            {label: '项目状态', name: 'projectStatus', sortable: false, index: 'project_status'},
            {label: '项目经理', name: 'projectManager', sortable: false, index: 'project_manager'},
            {label: '当前任务', name: 'projectTask', sortable: false, index: 'projectTask'},
            {label: '任务状态', name: 'projectTaskStatus', sortable: false, index: 'projectTaskStatus', width: 80},
            {
                label: '操作', name: 'endTime', width: 50, sortable: false, formatter: function (value, options, row) {
                // console.log('当前项目id' + row.id);
                return '<a class="btn-details" href="javascript:void(0);" data-id="' + row.id + '">' + '详情' + '</a>';
            }
            }
        ],
        viewrecords: true,
        height: 'auto',
        rowNum: 5,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            $('#jqGrid').on('click', '.btn-details', function (e) {
                // console.log($(this));
                // console.log($(this).attr('data-id'));
                var projectId = $(this).attr('data-id');
                var pWindow = window.parent;

                // console.log(pWindow.indexVm.$data);
                // console.log(pWindow.indexVm.main);
                // console.log(pWindow.indexVm.navTitle);

                // 改变首页的 indexVm 的 data，触发 updated
                pWindow.indexVm.main = 'modules/project/projectdetails.html?projectId=' + projectId;

                var oIframe = $('#main-content iframe', pWindow.document);
                pWindow.location.hash = 'modules/project/projectdetails.html?projectId=' + projectId;
                oIframe.attr('src', 'modules/project/projectdetails.html?projectId=' + projectId);
            })
        }
    });

    /* 主页项目检索-更多按钮跳转 */
    $('#btn-more').on('click', function () {
        var pWindow = window.parent;
        var oIframe = $('#main-content iframe', pWindow.document);
        pWindow.location.hash = 'modules/project/projectentity.html';
        oIframe.attr('src', 'modules/project/projectentity.html');
    });


    // SLIMSCROLL FOR CHAT WIDGET
    // 消息留言 滚动初始化
    $('#chat-box').slimScroll({
        height: '250px'
    });

    // 系统通知 滚动初始化
    $('#notification-box').slimScroll({
        height: '250px'
    });

});

var vm = new Vue({
    el:'#rrapp',
    data: {
        msgList: [],
        notificationList: [],
        meetingList:[]
    },
    created: function () {
        $.get(baseURL + 'generator/prjectmessage/queryUserMessage/' + user.userId, {token: token}, function (result) {
            // console.log(result);
            vm.msgList = result.prjectMessage;
            // console.log(vm.msgList);
            console.log(vm.msgList.length)
        });

        $.get(baseURL + 'generator/notificationreceiver/queryUserNotification/' + user.userId, {token: token}, function (result) {
            // console.log(result);
            vm.notificationList = result.notificationList;
            // console.log(vm.notificationList.length)
        });
        $.get(baseURL + 'generator/conferencesummary/mainQueryConferenceSummary/' + user.userId, {token: token}, function (result) {
            console.log(result);
            vm.meetingList = result.summaryList;
            $('#meeting-bubble').html(result.size);
        });
    },
    methods: {
        saveOrUpdate: function (conferenceId,projectId) {
            var layerIndex = layer.load(1);
            var data = {
                conferenceId:conferenceId,
                meetingStaff:user.userId
            };
            $.ajax({
                type: "POST",
                headers: {
                    token: "" + token
                },
                url: baseURL + "generator/conferencestaff/conferenceTagging",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (r) {
                    if (r.code === 0) {
                        var pWindow = window.parent;
                        pWindow.indexVm.main = 'modules/project/conferenceaccessory.html?conferenceId=' + conferenceId + '&projectId='+projectId;
                        pWindow.location.hash = 'modules/project/conferenceaccessory.html?conferenceId=' + conferenceId + '&projectId='+projectId;
                    } else {
                        layer.close(layerIndex);
                        alert(r.msg);
                    }
                }
            });
        }
    }
});
